﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Mr.LinqToWeibo
{
	internal class MethodCallExpressionFinder
        : ExpressionVisitor
	{
		private Expression rootExpression;
		private MethodCallExpression targetExpression;
		private string methodName;

		public MethodCallExpressionFinder (Expression rootExpression)
		{
			if (rootExpression == null) {
				throw new ArgumentNullException ("rootExpression");
			}
			this.rootExpression = rootExpression;
		}

		public MethodCallExpression Find (string methodName)
		{
			this.targetExpression = null;
			this.methodName = methodName;
			this.Visit (this.rootExpression);
			return targetExpression;
		}

		protected override Expression VisitMethodCall (MethodCallExpression m)
		{
			if (m.Method.Name == this.methodName) {
				this.targetExpression = m;
			}
			return base.VisitMethodCall (m);
		}
	}
}
